// 静态资源服务器

// 可以访问以下地址试试：
// http://localhost:9013/a.js
// http://localhost:9013/a.css
// http://localhost:9013/a.png
// http://localhost:9013/a.html

const http = require('http');
const fs = require('fs');
const path = require('path');
let mimes = {
    html: 'text/html',
    css: 'text/css',
    js: 'text/javascript',
    png: 'image/png',
    jpg: 'image/jpeg',
    gif: 'image/gif',
    ico: 'image/x-icon',
    svg: 'image/svg+xml',
    json: 'application/json',
    xml: 'application/xml',
    pdf: 'application/pdf',
    zip: 'application/zip',
    mp3: 'audio/mpeg',
    mp4: 'video/mp4',
}

const server = http.createServer((req, res) => {
    if (req.method !== 'GET') {
        res.statusCode = 405;
        res.end('<h1>405 Method Not Allowed</h1>')
        return false;
    }
    let {pathname} = new URL(req.url, 'http://127.0.0.1:9013');
    //console.log(new URL(req.url, 'http://127.0.0.1:9013'))
    let root = __dirname + '/static'
    let filePath = root + pathname
    fs.readFile(filePath, (err, data) => {
        if (err) {
            res.setHeader('Content-Type', 'text/html;charset=utf-8')
            switch (err.code) {
                case 'ENOENT':
                    res.statusCode = 404;
                    res.end('<h1>404 Not Found</h1>')
                case 'EPERM':
                    res.statusCode = 403;
                    res.end('<h1>没有访问权限</h1>')
                default:
                    res.statusCode = 500;
                    res.end('<h1>服务器内部错误</h1>')
            }
        } else {
            let ext = path.extname(filePath).slice(1) //获取文件的后缀名
            console.log(ext)
            let type = mimes[ext]
            if (type) {
                if (ext === 'html') {
                    res.setHeader('Content-Type', type + ';charset=utf-8')
                } else {
                    res.setHeader('Content-Type', type)
                }
            } else {
                res.setHeader('Content-Type', 'application/octet-stream')
            }
            res.end(data)
        }
    })
});

server.listen(9013, () => {
    console.log('服务启动完成')
});